import re
import html
from urllib import parse
import requests

GOOGLE_TRANSLATE_URL = 'http://translate.google.com/m?q=%s&tl=%s&sl=%s'

arr = {
    "厂商代码":"厂商代码",
    "模块电池电压低":"模块电池电压低",
}
res = {}
def translate(text, to_language="auto", text_language="auto"):

    text = parse.quote(text)
    url = GOOGLE_TRANSLATE_URL % (text,to_language,text_language)
    response = requests.get(url)
    data = response.text
    expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
    result = re.findall(expr, data)
    if (len(result) == 0):
        return ""

    return html.unescape(result[0])
#to_lan_arr = ["en"]
to_lan_arr = ["en","de","el","es","fr","hu","it","pl","pt","ro","ar","th","en"] #"en",
#to_lan_arr = ["el"]
for to_lan in to_lan_arr:
    with open("fanyi.txt", "a+", encoding="utf-8") as f:
        f.write(to_lan+'\n')
        #循环arr得到key的内容
        for key in arr:
            one_res = translate(key, to_lan, "zh-CN")
            #print(one_res)
            #对当前目录的lt.txt 打开并写入key的内容
            lines = one_res.split(" ")
            for i in range(len(lines)):
                lines[i] = lines[i].capitalize()
                linestr_new = " ".join(lines)
                if i==0:
                  print(linestr_new)
                  f.write('"'+key + '":"' + linestr_new + '",\n')


    #获取lt.txt 的内容，并且按照每行进行循环 增加,
    # with open("lt.txt", "r", encoding="utf-8") as f:
    #     lines = f.readlines()
    #     for line in lines:
    #         #print(line)
    #         with open("lt2.txt", "a+", encoding="utf-8") as f:
    #             #line首字母都变成大写
    #             #按照空格进行分割
    #             line_two = line.split(":")
    #             lines = line_two[1].replace('"',"").split(" ")
    #             for i in range(len(lines)):
    #               lines[i] = lines[i].capitalize()
    #             linestr_new = " ".join(lines)
    #             line = line_two[0]+":"+'"'+linestr_new+'"'
    #             f.write(line.replace("\n", "")+",\n")
